<?php
// +----------------------------------------------------------------------
// | Description: 图片上传
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

// use think\Request;
// use think\Controller;

class Upload extends ApiCommon
{   
    public function index()
    {   
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: POST');
        header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

        $file = request()->file('file');
        $name = request()->post('name');
        $name = explode('.',$name)[0];

        if (!$file) {
            return resultArray(['error' => '请上传文件']);
        }

        $path=ROOT_PATH . DS . 'uploads';
        $info = $file->validate(['ext'=>'xlsx,csv'])->move($path);
        // 上传成功
        if ($info) {

            require_once '/vendor/PHPExcel-1.8/Classes/PHPExcel.php';
            $filename=$info->getSaveName();

            $objReader = \PHPExcel_IOFactory::createReaderForFile($path.'\\'.$filename);
            $objPHPExcel = $objReader->load($path.'\\'.$filename);
            $sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
            
            $dataModel = model('Data');
            $param = array(
                'name'=>$name,
                'content'=>json_encode($sheetData),
                'create_time'=>time(),
                'user_id'=>$GLOBALS['userInfo']['id'],
                );
            $data = $dataModel->createData($param);
            if (!$data) {
                return resultArray(['error' => $dataModel->getError()]);
            } 
            return resultArray(['data' => '操作成功']);         

            // return resultArray(['data' =>  'uploads'. DS .$info->getSaveName()]);
        }

        // 上传失败
        
        return resultArray(['error' =>  $file->getError()]);
    }
}
